<?php

namespace App\Http\Controllers\Admin\Dispatch;

use App\Http\Controllers\Controller;
use App\Models\DepositModel;
use App\Models\DictionaryModel;
use App\Models\OrderModel;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Validator;

//留仓
class Deposit extends Controller
{

    //未配载入仓单
    public function list(Request $request) {
        $page = $request->input('page', 1);
        $limit = $request->input('limit', 10);
        $customer_name = $request->input('customer_name', '');
        $order_sn = $request->input('keyword', '');
        $goods_attr = $request->input('goods_attr', '');
        $des_country_id = $request->input('des_country_id', 0);
        $clearance_mode = $request->input('clearance_mode', '');
        $customer_type_id = $request->input('customer_type_id', '');
        $is_clearance = $request->input('is_clearance', '');
        $pre_out_date_start = $request->input('pre_out_date_start', '');
        $pre_out_date_end = $request->input('pre_out_date_end', '');

        $query = OrderModel::query()->with(['customer'])
            ->where('status', '>=', OrderModel::STATUS_CONFIRM)
            ->where('is_load', 1);


        if($customer_name){
            $query->whereHas('customer', function($q) use ($customer_name) {
                $q->where('name', 'like', "%{$customer_name}%");
            });
        }

        if($order_sn){
            $query->where('sn', $order_sn);
        }

        if($goods_attr){
            $query->where('goods_attr', $goods_attr);
        }

        if($des_country_id){
            $query->where('destination', $des_country_id);
        }

        if($clearance_mode){
            $query->where('clearance_mode', $clearance_mode);
        }

        if($is_clearance){
            $query->where('is_clearance', $is_clearance);
        }

        if($pre_out_date_start && $pre_out_date_end){
            $query->whereBetween('pre_out_date', [$pre_out_date_start, $pre_out_date_end]);
        }

        $total = $query->count('id');
        $orders = $query
            ->offset(($page-1) * $limit)
            ->limit($limit)
            ->orderBy('id', 'desc')
            ->get();

        $sum_weight = 0;
        $sum_big_pkgs = 0;
        $list = $orders->map(function($order) use (&$sum_big_pkgs, &$sum_weight) {
//            $load_pkgs = $order->big_pkgs - $order->load_pkgs_surplus;
//            $load_weight = $order->big_pkgs - $order->surplus_weight;

            $weight = $order->storage_weight - $order->load_weight;
            $big_pkgs = $order->big_pkgs - $order->load_pkgs;
            $sum_weight += $weight;
            $sum_big_pkgs += $big_pkgs;

            return [
                'id' => $order->id,
                'customer_name' => $order->customer->name ?? '',
                'customer_sn' => $order->customer->sn ?? '',
                'customer_type' => $order->customer->customer_type->name ?? '',
                'sn' => $order->sn,
                'storage_time' => $order->storage_time,
                'pre_out_date' => $order->pre_out_date,
                'des_country' => $order->destination,
                'goods_attr_name' => OrderModel::GOODS_ATTR_MAPS[$order->goods_attr] ?? '',
                'big_pkgs' => $big_pkgs,
                'pre_weight' => $weight,
            ];
        });

        return $this->success(['list' => $list, 'total' => $total,'sum_weight' => $sum_weight, 'sum_big_pkgs' => $sum_big_pkgs]);

    }

    //留仓列表
    public function list_old(Request $request) {
        $page = $request->input('page', 1);
        $limit = $request->input('limit', 20);
        $order_sn = $request->input('order_sn', '');
        $create_start = $request->input('create_start', '');
        $create_end = $request->input('create_end', '');

        $query = DepositModel::query()->with(['create_admin'])->whereHas('order', function($query) use ($order_sn) {
            $query->where('sn', 'like', '%'.$order_sn.'%');
        });

        if($create_start && $create_end){
            $query = $query->whereBetween('created_at', [$create_start, $create_end]);
        }

        $total = $query->count('id');
        $items = $query
            ->offset(($page-1) * $limit)
            ->limit($limit)
            ->orderBy('id', 'desc')
            ->get();

        //留仓重量
        $sum_weight = OrderModel::whereIn('id', function($query) {
            $query->select('order_id')->from((new DepositModel)->getTable());
        })->sum('pre_weight');

        //留仓件数
        $sum_big_pkgs = OrderModel::whereIn('id', function($query) {
            $query->select('order_id')->from((new DepositModel)->getTable());
        })->sum('big_pkgs');

        $list = $items->map(function($item) {
            $packages = DictionaryModel::whereIn('id', explode(',', $item->packages))
                    ->pluck('name');
            return [
                'id' => $item->id,
                'customer_name' => $item->order->customer->name ?? '',
                'customer_sn' => $item->order->customer->sn ?? '',
                'sn' => $item->order->sn ?? '',
                'storage_time' => $item->order->storage_time ?? '',
                'des_country' => $item->order->airport->country_name ?? '',
                'big_pkgs' => $item->order->big_pkgs ?? 0,
                'pre_weight' => $item->order->pre_weight ?? 0,
                'packages_name' => $packages,
                'created_at' => $item->created_at->toDateTimeString(),
                'remark' => $item->remark,
                'source' => DepositModel::SOURCE_MAPS[$item->source] ?? '',
                'create_admin_name' => $item->create_admin->staff->name ?? '',
            ];
        });

        return $this->success([
            'list' => $list,
            'total' => $total,
            'sum_weight' => $sum_weight,
            'sum_big_pkgs' => $sum_big_pkgs
        ]);
    }

    //留仓登记
    public function add(Request $request){
        $params = $request->all();
        $validator = Validator::make($params, [
            'sn' => 'required',
        ], [
            'sn.required' => '请填写入仓号',
        ]);

        if ($validator->fails()) {
            return $this->error($validator->errors()->first());
        }

        $order = OrderModel::where('sn', $params['sn'])->first();
        if(!$order){
            return $this->error('入仓单不存在');
        }

        $e = DepositModel::where('order_id', $order->id)->first();
        if($e) {
            return $this->error('该订单已登记留仓');
        }

        $auth = $request->get('auth');

        $deposit = new DepositModel();
        $deposit->order_id = $order->id;
        $deposit->created_admin_id = $auth->id;
        $deposit->remark = $params['remark'] ?? '';
        $deposit->save();
        return $this->success();
    }

    //取消留仓
    public function cancel(Request $request) {
        $ids = $request->input('ids');
        if(!is_array($ids)) {
            return $this->success();
        }

        DepositModel::whereIn('id', $ids)->delete();

        return $this->success();
    }

}
